package se.wobbia.android.net;

import java.util.LinkedList;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;

public class UploadTask extends AsyncTask<Void, String, Object> {
	private Context context;

	public UploadTask(Context context) {
		this.context = context;
	}

	@Override
	protected Object doInBackground(Void... params) {
		Bundle upload_info = null;
		while (m_uploads.size() > 0) {
			upload_info = m_uploads.get(0);
			if (upload_info != null) {
				// publishProgress(new String[]{"start",
				// upload_info.getString("title")});
				JSONObject result = new HttpProxyMonitored((String) upload_info
						.get("url"), context).run(upload_info);
				// publishProgress(new String[]{"start",
				// upload_info.getString("title")});
				m_uploads.remove();
				if (result == null || result.has("fail")) {
					String err_str = null;
					try {
						err_str = (result == null) ? "Unknown Failure" : result
								.getString("fail");
					} catch (JSONException e) {
						err_str = "Unknown Failure";
					}
					publishProgress("fail", err_str);
					m_uploads.clear();
				}
			}
		}

		return null;
	}

	@Override
	protected void onPostExecute(Object result) {
		// When all uploads are finished, kill the status bar upload
		// notification and stop the
		// Uploader service.
		// Toast.makeText("Upload(s) Completed", Toast.LENGTH_SHORT).show();
	}

	public void addUpload(Bundle upload_info) {
		if (m_uploads == null) {
			m_uploads = new LinkedList<Bundle>();
		}
		m_uploads.add(upload_info);
	}

	public LinkedList<Bundle> getUploads() {
		return new LinkedList<Bundle>(m_uploads);
	}

	private LinkedList<Bundle> m_uploads = null;
}
